package com.speedchina.oauth2_permission.config.smscode;

import com.speedchina.permission.domain.sys.entity.Role;
import com.speedchina.permission.service.sys.ResourceService;
import com.speedchina.permission.service.sys.RoleService;
import com.speedchina.permission.service.sys.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SmsUserDetailsService implements UserDetailsService {

    @Autowired
    public UserService userService;

    @Autowired
    public RoleService roleService;

    @Autowired
    public ResourceService resourceService;

    @Override
    public UserDetails loadUserByUsername(String tel) throws UsernameNotFoundException {
        com.speedchina.permission.domain.sys.entity.User user = userService.getByUserPhone(tel);
        Set<GrantedAuthority> authorities = new HashSet<>();
        List<Role> roles = roleService.findByUserId(user);
        for (Role role : roles){
            authorities.add(new SimpleGrantedAuthority(role.getRoleKey()));
        }
        Set<String> set = resourceService.getPermissions(user.getId());
        for (String resource : set){
            authorities.add(new SimpleGrantedAuthority(resource));
        }
        return new User(user.getUsername(), user.getPassword(),authorities);
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    public void setResourceService(ResourceService resourceService) {
        this.resourceService = resourceService;
    }

}
